<template>
  <div class="max-w-3xl mx-auto p-6">
    <h1 class="text-2xl font-semibold">查找并替换（Replace）</h1>

    <div class="mt-6 space-y-4">
      <label class="block">
        <div class="text-sm text-gray-600 mb-2">源文本（Source text）</div>
        <textarea v-model="inputText" rows="8" class="w-full p-3 border rounded resize-y" placeholder="在此粘贴或输入文本"></textarea>
      </label>

      <div class="grid grid-cols-1 sm:grid-cols-3 gap-3">
        <label class="col-span-1 sm:col-span-1 block">
          <div class="text-sm text-gray-600 mb-2">查找（Find）</div>
          <input v-model="findText" class="w-full p-2 border rounded" placeholder="要查找的文本或正则表达式" />
        </label>

        <label class="col-span-1 sm:col-span-1 block">
          <div class="text-sm text-gray-600 mb-2">替换为（Replace）</div>
          <input v-model="replaceText" class="w-full p-2 border rounded" placeholder="替换为..." />
        </label>

        <div class="col-span-1 sm:col-span-1 flex flex-col justify-between">
          <div class="flex items-center gap-3">
            <label class="inline-flex items-center">
              <input type="checkbox" v-model="isRegex" class="form-checkbox" />
              <span class="ml-2 text-sm">使用正则</span>
            </label>
            <label class="inline-flex items-center">
              <input type="checkbox" v-model="caseSensitive" class="form-checkbox" />
              <span class="ml-2 text-sm">区分大小写</span>
            </label>
            <label class="inline-flex items-center">
              <input type="checkbox" v-model="replaceAll" class="form-checkbox" />
              <span class="ml-2 text-sm">全部替换</span>
            </label>
          </div>

          <div class="mt-2">
            <input type="file" accept=".txt" @change="onFileChange" class="text-sm" />
          </div>
        </div>
      </div>

      <div class="flex items-center gap-3">
        <button @click="applyReplace" class="bg-blue-600 text-white px-4 py-2 rounded">应用替换</button>
        <button @click="copyResult" class="border px-3 py-2 rounded">复制结果</button>
        <button @click="downloadResult" class="border px-3 py-2 rounded">下载结果</button>
        <button @click="reset" class="border px-3 py-2 rounded text-sm">重置</button>
      </div>

      <div class="pt-4 border-t">
        <div class="flex justify-between items-center">
          <div class="text-sm text-gray-600">预览（Preview） — 替换后文本</div>
          <div class="text-sm text-gray-500">替换次数：<span class="font-medium">{{ replaceCount }}</span></div>
        </div>
        <textarea :value="replacedText" rows="8" class="w-full p-3 border rounded mt-3 bg-gray-50" readonly></textarea>
      </div>

      <nuxt-link to="/text-tools" class="mt-2 inline-block text-blue-500">返回文本工具</nuxt-link>
    </div>
  </div>
</template>

<script setup>
import { ref, computed } from 'vue'
import { useTools } from '~/composables/useTools'

const { copyToClipboard, downloadFile, readFile } = useTools()

const inputText = ref('')
const findText = ref('')
const replaceText = ref('')
const isRegex = ref(false)
const caseSensitive = ref(true)
const replaceAll = ref(true)
const regexError = ref('')

const escapeRegExp = (str) => {
  return str.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
}

const buildRegExp = () => {
  if (!findText.value) return null
  try {
    if (isRegex.value) {
      const flags = (replaceAll.value ? 'g' : '') + (caseSensitive.value ? '' : 'i')
      return new RegExp(findText.value, flags)
    } else {
      const pattern = escapeRegExp(findText.value)
      const flags = (replaceAll.value ? 'g' : '') + (caseSensitive.value ? '' : 'i')
      return new RegExp(pattern, flags)
    }
  } catch (err) {
    regexError.value = err.message || String(err)
    return null
  }
}

const replacedText = computed(() => {
  regexError.value = ''
  if (!findText.value) return inputText.value
  const re = buildRegExp()
  if (!re) return inputText.value
  try {
    return inputText.value.replace(re, replaceText.value)
  } catch (err) {
    regexError.value = err.message || String(err)
    return inputText.value
  }
})

const replaceCount = computed(() => {
  if (!findText.value) return 0
  const re = buildRegExp()
  if (!re) return 0
  const matches = inputText.value.match(new RegExp(re.source, 'g' + (re.flags.includes('i') ? 'i' : '')))
  return matches ? matches.length : 0
})

const applyReplace = () => {
  inputText.value = replacedText.value
}

const copyResult = async () => {
  const ok = await copyToClipboard(replacedText.value)
  if (ok) alert('已复制到剪贴板')
  else alert('复制失败，请手动复制')
}

const downloadResult = () => {
  downloadFile(replacedText.value, 'replace-result.txt', 'text/plain')
}

const reset = () => {
  inputText.value = ''
  findText.value = ''
  replaceText.value = ''
  isRegex.value = false
  caseSensitive.value = true
  replaceAll.value = true
  regexError.value = ''
}

const onFileChange = async (e) => {
  const f = e.target.files && e.target.files[0]
  if (!f) return
  try {
    const content = await readFile(f)
    inputText.value = content
  } catch (err) {
    console.error('读取文件失败', err)
    alert('读取文件失败')
  }
}
</script>
